<?php

namespace app\common\model;

use think\Model;

class MoneyLogModel extends BaseModel
{
    public $autoWriteTimestamp = true;
    public $createTime = 'add_time';

    public static function getType($id='')
    {
        $lst = [0 => '全部', 1 => '手动充值', 2 => '在线充值', 3 => '下单支付', 4 => '订单退款'];
        return $id ? $lst[$id] : $lst;
    }

    public static function addLog($user_id, $money, $type, $info = '', $log_no = '')
    {
        $user = UserModel::where('id', $user_id)->find();
        if (!$user){
            return self::setErrorInfo('用户不存在');
        }
        $balance = $user['balance'] + $money;
        if ($balance < 0 && $money < 0) {
            return self::setErrorInfo('余额不足a');
        }

        $user->save(['balance' => $balance]);
        return self::create([
            'user_id' => $user_id,
            'money' => $money,
            'now_money' => $balance,
            'type' => $type,
            'name' => self::getType($type),
            'info' => $info,
            'log_no' => $log_no
        ]);
    }
}
